package com.mobile.collect.present;

import android.text.TextUtils;

import com.mobile.collect.activitys.MainActivity;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.utils.LogRecordUtils;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.mvp.XPresent;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainPresent extends XPresent<MainActivity> {
    long startTime;
    long endTime;


    public void getDeviceList(final String searchName) {
        Observable.just(searchName).subscribeOn(Schedulers.io()).delay(1, TimeUnit.SECONDS).map(new Func1<String, List<DeviceInfo>>() {
            @Override
            public List<DeviceInfo> call(String searchName) {
                List<DeviceInfo> list;
                if (TextUtils.isEmpty(searchName)) {
                    list = EntityManager.getInstance().queryAllDeviceInfo();
                } else {
                    list = EntityManager.getInstance().queryDeviceInfoByName(searchName);
                }
                for (DeviceInfo deviceInfo : list) {
                    if (deviceInfo.getPointCount() == 0) {
                        int allCount = countPointTop(deviceInfo);
                        deviceInfo.setPointCount(allCount);
                        EntityManager.getInstance().saveDeviceInfo(deviceInfo);
                    }
                }
                return list;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<DeviceInfo>>() {
            @Override
            public void call(List<DeviceInfo> list) {
                getV().onSuccess(true, list);
            }
        });
    }

    private int countPointTop(DeviceInfo deviceInfo) {
        List<DevicePicInfo> picInfos = deviceInfo.getDevicePicList();
        int allCount = 0;
        for (DevicePicInfo picInfo : picInfos) {
            long count = picInfo.getPointCount();
            if (count == 0) {
                List<DevicePointInfo> pointInfos = picInfo.getPointList();
                for (DevicePointInfo pointInfo : pointInfos) {
                    String childTypeEn = pointInfo.getChildTypeEn();
                    if ("KP".equals(childTypeEn)) {
                        count += pointInfo.getDeviceCount();
                    } else {
                        count++;
                    }
                }
                picInfo.setPointCount(count);
                EntityManager.getInstance().saveDevicePicInfo(picInfo);
            }
            allCount += count;
        }
        return allCount;
    }
}
